﻿using Duo1JHttpServer.Framework.Config;
using Duo1JHttpServer.Framework.Enum;
using Duo1JHttpServer.Framework.Interface;
using Duo1JHttpServer.Framework.Model;
using Duo1JHttpServer.Framework.Utils;

namespace Duo1JHttpServer.Framework.Server
{
    internal sealed class RequestDispatcher
    {
        /// <summary>
        /// 解析URL并分发
        /// </summary>
        public static void Dispatch(RequestModel requestModel)
        {
            if (HtmlHandler.HandleHtml(requestModel))
            {
                return;
            }

            if (ConfigManager.FilterConfig.FilterDic.TryGetValue(requestModel.RequestUrl, out IHttpFilter filter))
            {
                if (!filter.DoFilter(requestModel))
                {
                    ConsoleUtils.WriteRedLine($"Filter reject request: {requestModel.RequestUrl}");
                    return;
                }
            }

            if (ConfigManager.HandlerConfig.HandleDic.TryGetValue(requestModel.RequestUrl, out IHttpHandle handle))
            {
                handle.SetModel(requestModel);
                switch (requestModel.RequestType)
                {
                    case RequestType.Get:
                        handle.HandleGet();
                        break;
                    case RequestType.Post:
                        handle.HandlePost();
                        break;
                    case RequestType.Unknown:
                        break;
                    default:
                        DispatchToNotFound(requestModel);
                        break;
                }
            }
            else
            {
                DispatchToNotFound(requestModel);
            }
        }

        /// <summary>
        /// 导航到404
        /// </summary>
        private static void DispatchToNotFound(RequestModel requestModel)
        {
            StaticHandler.RequestNotFound(requestModel);
        }
    }
}